package com.youhong.teethcare;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.customviews.BatteryView;
import com.youhong.teethcare.customviews.CountDownmageView;
import com.youhong.teethcare.dialogs.BrushModeDialog;
import com.youhong.teethcare.dialogs.ChargeNotificationDialog;
import com.youhong.teethcare.dialogs.LowBatteryDialog;
import com.youhong.teethcare.javabeans.BrushingRecord;
import com.youhong.teethcare.javabeans.JstyleDevice;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.utils.DBHelper;
import com.youhong.teethcare.utils.ImageUtils;
import com.youhong.teethcare.utils.PreferencesUtils;
import com.youhong.teethcare.utils.Util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class DashBoardFragment extends Fragment implements View.OnClickListener, BrushModeDialog.LimitValueListener {

    private TextView tv_Level;
    private LinearLayout btMore;
    private TextView tv_brushMode, tv_dashTime;
    private TextView bt_CustomModeName;

    public DashBoardFragment() {
        // Required empty public constructor
    }

    TextView tv_name;
    ImageView iv_connect, iv_portrait;
    TextView tv_PointLevel, tv_points;
    ImageView iv_level;
    TextView tv_durationMins,
            tv_duration_seconds,
            tv_frequencyDay,
            tv_surfacePercent;

    LinearLayout rl_duration, rl_frequency, rl_surface;
    RelativeLayout rl_brushMode, rl_brushTime;
    Unbinder unbinder;
    LinearLayout bt_StartBrush;
    @BindView(R.id.dashboard_tv_connect)
    TextView tv_connect;
    @BindView(R.id.dashboard_tv_battery)
    TextView tv_battery;

    @BindView(R.id.ll_Score)
    LinearLayout ll_Score;
    @BindView(R.id.rl_bg)
    RelativeLayout rl_bg;
    @BindView(R.id.iv_Top)
    ImageView iv_Top;
    @BindView(R.id.rl_dashName)
    RelativeLayout rl_dashName;
    @BindView(R.id.rl_customMode)
    RelativeLayout rl_customMode;
    @BindView(R.id.rl_strength)
    RelativeLayout rl_strength;
    String[] modes;
    List<String> diyString;
    List<String> modeString;
    List<String> lvString;
    List<String> timeString;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_dashboard, container, false);
        unbinder = ButterKnife.bind(this, v);

        getViews(v);
        initData();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);

        tv_name.setText(Common.userInfo.getNickName());

        Calendar c = Calendar.getInstance();

        //计算面板上数据显示
        List<BrushingRecord> list_year_groupByDay_all = DBHelper.getDbHelper(getContext()).queryBrushRecordGroupByYearDay(c.get(Calendar.YEAR), 1);

        List<BrushingRecord> list_year = DBHelper.getDbHelper(getContext()).queryBrushRecordByYear(c.get(Calendar.YEAR), 1);
        List<BrushingRecord> list_year_realTime = DBHelper.getDbHelper(getContext()).queryBrushRecordByYear(c.get(Calendar.YEAR), BrushingRecord.REAL_TIME_DATA);

        int count_duration = 0, count_frequency = 0, percentCount = 0;
        for (BrushingRecord record : list_year) {

            count_duration += record.getTotalTime();
        }

        for (BrushingRecord record : list_year_realTime) {

            percentCount += record.getPercent();

        }


        for (BrushingRecord record : list_year_groupByDay_all) {

            count_frequency += record.getCount();
        }

        //计算Surface 平均数。
        if (list_year_realTime.size() != 0) {
            percentCount = percentCount / list_year_realTime.size();
        }

        if (list_year.size() != 0) {

            count_duration = count_duration / list_year.size();

        }

        if (list_year_groupByDay_all.size() != 0) {

            count_frequency = count_frequency / list_year_groupByDay_all.size();

        }
        tv_durationMins.setText(count_duration / 60 + "");
        tv_duration_seconds.setText(Util.concateZero(count_duration % 60));

        tv_frequencyDay.setText(count_frequency + "");
        tv_surfacePercent.setText(percentCount + "%");


        getActivity().registerReceiver(receiver, filter);
       if(MainActivity.mDevice!=null) MainActivity.mDevice.getBattery();
        return v;
    }

    //    public void sendServiceSms() {
//        try {
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
//                SubscriptionManager subscriptionManager=(SubscriptionManager)getActivity().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
//                List<SubscriptionInfo>list=subscriptionManager.getActiveSubscriptionInfoList();
//                SubscriptionInfo subscriptionInfo=list.get(0);
//                int subId=subscriptionInfo.getSubscriptionId();
//                SmsManager manager = SmsManager.getSmsManagerForSubscriptionId(subId);
//
//
//                manager.sendTextMessage("10001", null, "68464", null, null);
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);

    }
    BatteryView batteryView;
    private void getViews(View v) {
        batteryView= v.findViewById(R.id.batteryView);
        tv_dashTime = v.findViewById(R.id.tv_dashTime);

        tv_brushMode = v.findViewById(R.id.tv_ModeName);
        bt_CustomModeName = v.findViewById(R.id.bt_CustomModeName);
        rl_brushMode = v.findViewById(R.id.dash_rl_brushMode);
        rl_brushMode.setOnClickListener(this);
        bt_StartBrush = v.findViewById(R.id.ll_start);
        bt_StartBrush.setOnClickListener(this);
        rl_brushTime = v.findViewById(R.id.dash_rl_brushTime);
        rl_brushTime.setOnClickListener(this);
        btMore = v.findViewById(R.id.ll_Score);
        btMore.setOnClickListener(this);
        rl_strength.setOnClickListener(this);
        rl_customMode.setOnClickListener(this);

        tv_surfacePercent = v.findViewById(R.id.dash_tv_surfacePercent);

        tv_durationMins = v.findViewById(R.id.dash_tv_durationMins);
        tv_duration_seconds = v.findViewById(R.id.dash_tv_durationSeconds);

        tv_frequencyDay = v.findViewById(R.id.dash_tv_frequency);


        rl_duration = v.findViewById(R.id.dash_rl_duration);
        rl_duration.setOnClickListener(this);

        rl_frequency = v.findViewById(R.id.dash_rl_frequency);
        rl_frequency.setOnClickListener(this);

        rl_surface = v.findViewById(R.id.dash_rl_surface);
        rl_surface.setOnClickListener(this);

        iv_connect = v.findViewById(R.id.dash_iv_connect);
        iv_portrait = v.findViewById(R.id.dash_iv_portrait);

        tv_name = v.findViewById(R.id.dash_tv_name);
        tv_Level = v.findViewById(R.id.dash_tv_brushLevel);

        iv_connect = v.findViewById(R.id.dash_iv_connect);
        iv_connect.setOnClickListener(this);
        tv_PointLevel = v.findViewById(R.id.dash_tv_level);
        tv_points = v.findViewById(R.id.dash_tv_points);
        iv_level = v.findViewById(R.id.dash_iv_level);
        showDeviceDisplay();
        showScore();
        showIcon();

        if (MainActivity.mDevice == null) {

            iv_connect.setImageDrawable(getResources().getDrawable(R.mipmap.icon_disconnect_little));

        } else {
            boolean isConnect = MainActivity.mDevice.isConnected();
            showDeviceState(isConnect);
        }
    }

    void showScore() {
        int score = Common.userInfo.getScore();

        //显示分数和刷牙等级
        tv_points.setText(score + "");

        if (score < 500) {

            tv_PointLevel.setText(getResources().getString(R.string.strings127) + "/" +
                    getResources().getString(R.string.strings138)
                    + "1");
            iv_level.setImageDrawable(getResources().getDrawable(R.drawable.item_score1));


        } else if (score < 2000) {

            tv_PointLevel.setText(getResources().getString(R.string.strings127) + "/" +
                    getResources().getString(R.string.strings138)
                    + "2");

            iv_level.setImageDrawable(getResources().getDrawable(R.drawable.item_score2));


        } else if (score < 5000) {

            tv_PointLevel.setText(getResources().getString(R.string.strings127) + "/" +
                    getResources().getString(R.string.strings138)
                    + "3");
            iv_level.setImageDrawable(getResources().getDrawable(R.drawable.item_score3));

        } else if (score < 10000) {

            tv_PointLevel.setText(getResources().getString(R.string.strings127) + "/" +
                    getResources().getString(R.string.strings138)
                    + "4");
            iv_level.setImageDrawable(getResources().getDrawable(R.drawable.item_score4));


        } else {

            tv_PointLevel.setText(getResources().getString(R.string.strings127) + "/" +
                    getResources().getString(R.string.strings138)
                    + "5");
            iv_level.setImageDrawable(getResources().getDrawable(R.drawable.item_score5));

        }


    }

    void initData() {
        int mode = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushMode);
        int lv = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushLv);
        int time = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushTime);
        int diyMode = PreferencesUtils.ReadFromPreferencesInt(getContext(), DiyMode);
        modes = getResources().getStringArray(R.array.brushModes);
        diyString = getData(BrushModeDialog.Type_Diy);
        modeString = getData(BrushModeDialog.Type_Mode);
        timeString = getData(BrushModeDialog.Type_Time);
        lvString = getData(BrushModeDialog.Type_Lv);
        showBrushMode(mode);
        showBrushDiyMode(diyMode);
        showBrushLevel(lv);
        showBrushTime(timeString.get(time));
    }

    void showDeviceState(boolean isConnect) {
        iv_connect.setImageDrawable(getResources().getDrawable(isConnect ? R.mipmap.icon_connect_little : R.mipmap.icon_disconnect_little));
        tv_connect.setText(getString(isConnect ? R.string.chosenDevice_str2 : R.string.chosenDevice_str3));
    }

    void showIcon() {
        ImageUtils.showIcon(iv_portrait);
    }

    void connect() {
        if (MainActivity.mDevice != null) {
            isManuallyDisconnected = true;
        }
        ((MainActivity) getActivity()).connect();
    }

    void showBrushMode(int mode) {
        String modeName = modeString.get(mode);
        tv_brushMode.setText(modeName);
    }
    void showBrushDiyMode(int mode) {
        String modeName = modes[mode];
        bt_CustomModeName.setText(modeName);
    }
    void showBrushLevel(int level) {

        tv_Level.setText(String.format(getString(R.string.brushLvFormat), level + 1));
    }

    void showBrushTime(String brushTime) {
        tv_dashTime.setText(brushTime);

    }

    void showDeviceDisplay() {
        JstyleDevice jstyleDevice = Util.getDevice();
        boolean needShowScore = jstyleDevice.needShowScore();
        //  boolean needShowScore=true;
        // ll_Score.setVisibility(needShowScore?View.VISIBLE:View.GONE);
        //ll_dashFunction.setVisibility(needShowScore?View.GONE:View.VISIBLE);
        rl_dashName.setVisibility(needShowScore ? View.GONE : View.VISIBLE);
        iv_Top.setVisibility(needShowScore ? View.GONE : View.VISIBLE);
//        if(needShowScore){
//            rl_bg.setBackgroundResource(R.mipmap.home_bg2);
//        }else {
//            rl_bg.setBackgroundColor(getResources().getColor(R.color.pageBackground));
//        }
    }

    @Override
    public void onClick(View v) {

        if (v == iv_connect) {

            connect();
        } else if (v == rl_duration) {
            // sendServiceSms();
            Intent intent = new Intent(getContext(), DurationAnalysisActivity.class);
            startActivity(intent);

        } else if (v == rl_frequency) {

            Intent intent = new Intent(getContext(), FrequencyAnalysisActivity.class);
            startActivity(intent);

        } else if (v == rl_surface) {

            Intent intent = new Intent(getContext(), SurfaceAnalysisActivity.class);
            startActivity(intent);
        } else if (v == rl_brushMode) {
            showBrushModeDialog(BrushModeDialog.Type_Mode, modeString);
        } else if (v == rl_brushTime) {
            showBrushModeDialog(BrushModeDialog.Type_Time, timeString);
        } else if (v == bt_StartBrush) {
            int mode = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushMode);

            ((MainActivity) getActivity()).switchToBrushFragment();
        } else if (v == rl_customMode) {
            showBrushModeDialog(BrushModeDialog.Type_Diy, diyString);
        } else if (v == rl_strength) {
            showBrushModeDialog(BrushModeDialog.Type_Lv, lvString);
        } else if (v == btMore) {
            Intent intent = new Intent(getContext(), PointsLevelActivity.class);
            startActivity(intent);
        }

    }

    private void showBrushModeDialog(int type, List<String> data) {
        if (MainActivity.mDevice == null || !MainActivity.mDevice.isConnected()) {
            connect();
            return;
        }
        int lowValue = 0;
        int highValue = 0;
        int mode = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushMode);
        int lv = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushLv);
        int time = PreferencesUtils.ReadFromPreferencesInt(getContext(), BrushTime);
        if (type == BrushModeDialog.Type_Time) {
            lowValue = time;
        } else {
            lowValue = mode;
          //  highValue = lv;
        }
        BrushModeDialog brushModeDialog = BrushModeDialog.newInstance(type, lowValue);
        brushModeDialog.setData(data);
        brushModeDialog.setLimitValueListener(this);
        brushModeDialog.show(getChildFragmentManager(), "");

    }

    void setDataToDevice(int type, int lowValue) {
        if (MainActivity.mDevice != null && MainActivity.mDevice.isConnected()) {
            if (type == BrushModeDialog.Type_Mode) {
                MainActivity.mDevice.setBrushingStatus(lowValue + 1);
            } else if (type == BrushModeDialog.Type_Time) {
                MainActivity.mDevice.setBrushingTimeType(lowValue);
            } else if (type == BrushModeDialog.Type_Diy) {
                MainActivity.mDevice.setBrushingDiy(lowValue + 1);
            } else if (type == BrushModeDialog.Type_Lv) {
                MainActivity.mDevice.setBrushingTime(lowValue, (lowValue + 1) * 20);
            }

        } else {
            //connect();
        }
    }

    final String BrushMode = "BrushMode";
    final String BrushLv = "BrushLv";
    final String BrushTime = "BrushTime";
    final String DiyMode = "BrushDiyMode";

    void saveBrushData(String key, int value) {
        PreferencesUtils.WriteToPreferencesInt(getContext(), key, value);
    }

    List<String> getData(int type) {
        List<String> data = new ArrayList<>();
        if (type == BrushModeDialog.Type_Time) {
            String format = getString(R.string.brush_timeFormat);
            for (int i = 3; i < 7; i++) {
                int time = i * 30;
                int mins = time / 60;
                int seconds = time % 60;
                data.add(String.format(format, mins, seconds));
            }
        } else if (type == BrushModeDialog.Type_Mode) {

            List<String> tempData = Arrays.asList(modes);
            for (int i = 0; i < 4; i++) {
                data.add(tempData.get(i));
            }
            //   data.add(getString(R.string.Customize));
        } else if (type == BrushModeDialog.Type_Diy) {

            data = Arrays.asList(modes);
        } else if (type == BrushModeDialog.Type_Lv) {
            for (int i = 1; i < 6; i++) {
                data.add(i + " Lv");
            }
        }
        return data;
    }


    boolean isManuallyDisconnected = false;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction() == BleService.ACTION_GATT_SERVICES_DISCOVERED) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //connectDialog.cancel();
                        iv_connect.setImageDrawable(getResources().getDrawable(R.mipmap.icon_connect_little));
                        tv_connect.setText(R.string.chosenDevice_str2);

                        ((MainActivity) getActivity()).handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                //连接成功后，立刻同步时间
                                MainActivity.mDevice.syncTime(Calendar.getInstance());
                            }

                        }, 500);
                    }
                });


            } else if (intent.getAction() == BleService.ACTION_GATT_DISCONNECTED) {

                if (isManuallyDisconnected) {

                    isManuallyDisconnected = false;
                    iv_connect.setImageDrawable(getResources().getDrawable(R.mipmap.icon_disconnect_little));
                    tv_connect.setText(R.string.chosenDevice_str1);
                    MainActivity.mDevice = null;

                } else {

                    Toast.makeText(context, R.string.strings20, Toast.LENGTH_SHORT).show();
                }
                showDeviceState(false);
            } else if (intent.getAction() == BleService.ACTION_DATA_AVAILABLE) {
                byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);
                if (values[0] == (byte)0x13) {
                    if (values[1] == 0) return;
                    Common.battery = values[1] & 0xFF;
                    tv_battery.setText(Common.battery + "%");
                    batteryView.updateBatteryValue(  Common.battery);
                    if (Common.battery <= 20 && Common.isLowBatteryNotificationPlayed == false) {
                        LowBatteryDialog dialog = new LowBatteryDialog(getActivity());
                        dialog.show();

                    }
                }

            }
        }
    };

    @Override
    public void limitValueCallBack(int type, int lowValue) {
        if (type == BrushModeDialog.Type_Mode) {
            saveBrushData(BrushMode, lowValue);
            showBrushMode(lowValue);
//            if(lowValue==4){
//                showBrushModeDialog(BrushModeDialog.Type_Diy,diyString);
//            }else {
//                showBrushModeDialog(BrushModeDialog.Type_Lv,lvString);
//            }

        } else if (type == BrushModeDialog.Type_Lv) {
            saveBrushData(BrushLv, lowValue);
            showBrushLevel(lowValue);
            //  showBrushModeDialog(BrushModeDialog.Type_Time,timeString);
        } else if (type == BrushModeDialog.Type_Time) {
            showBrushTime(timeString.get(lowValue));
            saveBrushData(BrushTime, lowValue);
        } else if (type == BrushModeDialog.Type_Diy) {
            saveBrushData(DiyMode, lowValue);
            showBrushDiyMode(lowValue);
            // showBrushModeDialog(BrushModeDialog.Type_Lv,lvString);
        }
        setDataToDevice(type, lowValue);
    }
}